//
//  WHNetworkTool.m
//  DishManager
//
//  Created by she1323 on 16/7/28.
//  Copyright © 2016年 she1323. All rights reserved.
//

#import "WHNetworkTool.h"
#import <AFNetworking.h>
#import "WHProgressHUD.h"
#import "YLSwitchRootController.h"
#import "YLAccountTool.h"
#import "YLLoginViewController.h"
static WHNetworkTool *_network;
static AFHTTPSessionManager *_manager;

@interface WHNetworkTool ()
@property (nonatomic, assign) NSInteger index;
@end

@implementation WHNetworkTool
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    
//    //1.创建网络状态监测管理者
//    AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
//    
//    __block NSInteger index = 0;
//    //2.监听改变
//    [manger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        
//        if (index > 0) {
//            switch (status) {
//                case AFNetworkReachabilityStatusUnknown:
//                    [WHProgressHUD showError:@"您已切换到未知网络"];
//                    NSLog(@"未知");
//                    break;
//                case AFNetworkReachabilityStatusNotReachable:
//                    [WHProgressHUD showError:@"您已没有网络"];
//                    break;
//                case AFNetworkReachabilityStatusReachableViaWWAN:
//                    [WHProgressHUD showSuccess:@"您已切换到蜂窝移动网络"];
//                    break;
//                case AFNetworkReachabilityStatusReachableViaWiFi:
//                    [WHProgressHUD showSuccess:@"您已切换到WIFI网络"];
//                    break;
//                default:
//                    break;
//            }
//        }
//       
//    
//        index ++;
//    }];
//    
//    [manger startMonitoring];
    
   static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _network = [super allocWithZone:zone];
        _manager = [AFHTTPSessionManager manager];
        _manager.requestSerializer = [AFJSONRequestSerializer serializer];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", @"text/json", @"application/json",nil ,nil];
        _manager.requestSerializer.timeoutInterval = 10.0f;
    });
    return _network;
}

- (void)setTimeOut:(double)timeOut
{
    _timeOut = timeOut;
    _manager.requestSerializer.timeoutInterval = timeOut;
}

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _network = [[self alloc] init];
    });
    return _network;
}

- (void)sendPostWithUrl:(NSString *)url params:(NSDictionary *)params success:(SuccessBlock)successBlock fail:(FailBlock)failBlock
{

    __weak typeof(self) weakSelf = self;
    [_manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        successBlock(responseObject[@"result"]);
        
         [_manager.requestSerializer clearAuthorizationHeader];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
        {
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
            if (responses.statusCode == 401) {
                
                [weakSelf loginFromOther];
//
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"dismissPassNoti" object:nil userInfo:nil];
//                [YLAccountTool noAccount];
//                [YLSwitchRootController switchRootController];
                //自己想要进行的操作
                
            } else {
                [WHProgressHUD checkNetPlease];
            }

        }
        
         [_manager.requestSerializer clearAuthorizationHeader];
    }];
}

- (void)sendPostWithUrl:(NSString *)url header:(NSDictionary *)header params:(NSDictionary *)params success:(SuccessBlock)successBlock fail:(FailBlock)failBlock
{
    
    __weak typeof(self) weakSelf = self;
    [header enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [_manager.requestSerializer setValue:obj forHTTPHeaderField:key];
    }];
    
    [_manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        successBlock(responseObject[@"result"]);
        [_manager.requestSerializer clearAuthorizationHeader];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
        {
            [WHProgressHUD dismiss];
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            
            if (responses.statusCode == 401) {
                [weakSelf loginFromOther];
                
                //自己想要进行的操作
            } else {
                
                
                [WHProgressHUD checkNetPlease];
            }
            
        }
         [_manager.requestSerializer clearAuthorizationHeader];
    }];
}

- (void)loginFromOther
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"dismissPassNoti" object:nil userInfo:nil];
    
    if ([YLAccountTool account]) {
        
        [YLAccountTool noAccount];
        [YLSwitchRootController switchRootController];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的账号在另一设备上登录，如非本人操作，请及时修改登录密码" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:okAction];
         [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
        
    }
    
   
    
    
    
    
    
    
   
}

- (void)sendGetWithUrl:(NSString *)url params:(NSDictionary *)params success:(SuccessBlock)successBlock fail:(FailBlock)failBlock
{
    
    [_manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)sendPostWithUrl:(NSString *)url params:(NSDictionary *)params constructingBodyWithBlock:(ConstructingBodyBlock)constructingBodyBlock success:(SuccessBlock)successBlock fail:(FailBlock)failBlock
{
    
    [_manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        constructingBodyBlock(formData);
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)cancel
{
    
    
    [_manager.operationQueue cancelAllOperations];
}
@end
